package xyz.lwm.lazycat.vertx;

import io.vertx.ext.web.RoutingContext;
import xyz.lwm.lazycat.utility.CollectionUtil;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.web.handle.Multipart;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Vertx Multipart form data
 *
 * @author lwm
 */
class VertxMultipart implements Multipart {

	private final Map<String, List<String>> paramListMap;

	private final Map<String, List<File>> fileListMap;

	private boolean loaded;

	VertxMultipart(RoutingContext rctx) {
		paramListMap = new HashMap<>();
		fileListMap = new HashMap<>();
		It.of(rctx.request().formAttributes()).filter(Objects::nonNull).also(map ->
				map.forEach(e ->
						paramListMap.computeIfAbsent(e.getKey(),
								k -> new ArrayList<>()).add(e.getValue())));
		It.of(rctx.fileUploads()).filter(CollectionUtil::isNotEmpty)
				.also(uploads -> loaded = true)
				.also(uploads -> uploads.forEach(upload ->
						fileListMap.computeIfAbsent(upload.name(), k -> new ArrayList<>())
								.add(new VertxUploadFile(upload, rctx.vertx().fileSystem()))));
	}

	@Override
	public Map<String, List<String>> getParamListMap() {
		return paramListMap;
	}

	@Override
	public Set<String> getParamNames() {
		return paramListMap.keySet();
	}

	@Override
	public String getParam(String paramName) {
		return It.of(paramListMap.get(paramName))
				.filter(CollectionUtil::isNotEmpty)
				.let(list -> list.get(0))
				.getOr(null);
	}

	@Override
	public List<String> getListParam(String paramName) {
		return paramListMap.get(paramName);
	}

	@Override
	public Map<String, List<File>> getFileListMap() {
		return fileListMap;
	}

	@Override
	public File getFile(String paramName) {
		return It.of(fileListMap.get(paramName))
				.filter(CollectionUtil::isNotEmpty)
				.let(list -> list.get(0))
				.getOr(null);
	}

	@Override
	public Set<String> getFileParamNames() {
		return fileListMap.keySet();
	}

	@Override
	public List<File> getFileList(String paramName) {
		return fileListMap.get(paramName);
	}

	@Override
	public boolean isLoaded() {
		return loaded;
	}

}
